package com.qipay.sp.impl;

import com.qipay.baas.model.Order;
import com.qipay.baas.model.SpUser;
import com.qipay.baas.model.SpUserExample;
import com.qipay.baas.model.User;
import com.qipay.core.entity.DicConstance;
import com.qipay.core.entity.Pagination;
import com.qipay.core.entity.ValueObject;
import com.qipay.core.help.BeanHelper;
import com.qipay.core.utils.CommUtil;
import com.qipay.mapper.OrderMapper;
import com.qipay.mapper.SpUserMapper;
import com.qipay.mapper.UserMapper;
import com.qipay.order.config.OrderChannelEnum;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.sp.SpUserService;
import com.qipay.sp.dto.SpUserOrderListDto;
import com.qipay.user.entity.UserLevel;
import com.qipay.user.service.UserService;
import com.qipay.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class SpUserServiceImpl implements SpUserService {

    @Autowired
    SpUserMapper spUserExtMapper;

    @Autowired
    UserService userService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderMapper orderMapper;

    @Override
    public List<ValueObject> query(Pagination pagination) {
        return Pagination.wrapper(() -> spUserExtMapper.myQuery(), pagination);
    }

    @Override
    public List<ValueObject> query() {
        return spUserExtMapper.myQuery();
    }

    @Override
    @Transactional
    public int delete(String name) {

        SpUserExample spUserExample = new SpUserExample();
        spUserExample.or().andNameEqualTo(name);
        spUserExtMapper.deleteByExample(spUserExample);

        userMapper.deleteByName(name);
        return 0;
    }

    @Override
    @Transactional
    public int add(String spUserName, BigDecimal feeRate) {
        //插入供号商名称
        SpUserExample spUserExample = new SpUserExample();
        spUserExample.or().andSpUserNameEqualTo(spUserName);
        List<SpUser> spUsers = spUserExtMapper.selectByExample(spUserExample);
        if (CommonUtil.isNotEmpty(spUsers)) {
            throw new RuntimeException("供号商名称重复");
        }

        SpUser spUser = new SpUser();
        spUser.setName("new");
        spUser.setSpUserName(spUserName);
        spUser.setFeeRate(feeRate);
        spUserExtMapper.insert(spUser);

        //取出id做用户名和密码
        String spUserID = String.valueOf(spUser.getId());
        String name = String.valueOf(spUserID);
        String pwd = String.valueOf(spUserID);
        spUser.setName(spUserID);

        //把ID回写成name
        spUserExtMapper.updateByPrimaryKey(spUser);

        //插入用户
        String newDBPassword = passwordEncoder.encode(pwd);
        User manager = new User();
        manager.setName(name);
        manager.setSex((byte) 1);
        manager.setPwd(newDBPassword);
        manager.setLevel(UserLevel.ADMIN_Hao.getCode());
        manager.setPid(0);
        //插入用户
        userService.insert(manager);
        return 200;
    }

    @Override
    public Map<String, String> selectSPUserName(List<String> userName) {
        SpUserExample spUserExample = new SpUserExample();
        spUserExample.or().andNameIn(userName);
        List<SpUser> spUsers = spUserExtMapper.selectByExample(spUserExample);
        Map<String, String> result = new HashMap<>();
        if (CommUtil.isNotEmpty(spUsers)) {
            spUsers.stream().forEach(s -> {
                result.put(s.getName(), s.getSpUserName());
            });
        }
        return result;
    }

    @Override
    public SpUserOrderListDto selectSpOrderList(Integer spId, String startTime, String endTime, Pagination pagination) {
        //这里可能要用那个sql吧
        //启用分页后调用
        List<ValueObject> orders = Pagination.wrapper(() -> orderMapper.selectSpUserOrders(spId, startTime, endTime), pagination);
        orders = orders.stream().map(this::fill).collect(Collectors.toList());

        SpUserOrderListDto spUserOrderListDto = orderMapper.selectSpUserOrdersTotal(spId, startTime, endTime);
        spUserOrderListDto.setTotalAmount((float) (Optional.ofNullable(spUserOrderListDto.getTotalAmount()).orElseGet(() -> new Float(0.0)) / 100.0));
        spUserOrderListDto.setPageList(orders);
        return spUserOrderListDto;
    }

    /**
     * 一些转换
     */
    private ValueObject fill(ValueObject o) {
        Order order = BeanHelper.valueObjectToBean(o, Order.class);
        o.put("actualAmount", Optional.ofNullable(order.getActualAmount()).orElseGet(() -> 0) / 100.0);
        o.put("advanceAmount", Optional.ofNullable(order.getAdvanceAmount()).orElseGet(() -> 0) / 100.0);
        o.put("amount", Optional.ofNullable(order.getAmount()).orElseGet(() -> 0) / 100.0);
        o.put("actualPayAmount", Optional.ofNullable(order.getActualPayAmount()).orElseGet(() -> 0) / 100.0);
        o.put("disableAmount", Optional.ofNullable(order.getDisableAmount()).orElseGet(() -> 0) / 100.0);
        o.put("fee", Optional.ofNullable(order.getFee()).orElseGet(() -> 0) / 100.0);
        o.put("spFee", Optional.ofNullable(order.getSpFee()).orElseGet(() -> 0) / 100.0);
        o.put("agentFee", Optional.ofNullable(order.getAgentFee()).orElseGet(() -> 0) / 100.0);

        o.put("stateName", OrderStateEnum.getInfo(order.getState()));
        o.put("channelName", OrderChannelEnum.getInfo(order.getChannelType()));
        return o;
    }
}
